import network
import time
import config

class WiFiManager:
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(True)
        
    def connect(self, timeout=30):
        """连接到WiFi网络"""
        if self.is_connected():
            print("已连接到WiFi")
            return True
            
        print(f"连接到WiFi: {config.WIFI_SSID}")
        self.wlan.connect(config.WIFI_SSID, config.WIFI_PASSWORD)
        
        start_time = time.time()
        while not self.is_connected() and time.time() - start_time < timeout:
            print("正在连接WiFi...")
            time.sleep(1)
            
        if self.is_connected():
            print(f"WiFi连接成功，IP地址: {self.wlan.ifconfig()[0]}")
            return True
        else:
            print("WiFi连接失败")
            return False
            
    def is_connected(self):
        """检查WiFi是否已连接"""
        return self.wlan.isconnected()
        
    def disconnect(self):
        """断开WiFi连接"""
        if self.is_connected():
            self.wlan.disconnect()
            print("已断开WiFi连接")
            
    def reconnect(self):
        """重新连接WiFi"""
        print("尝试重新连接WiFi...")
        self.disconnect()
        return self.connect()
